import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {EventBusService} from "../../../services/event-bus.service";
import {PublicService} from "../../../services/public.service";
import {StorageService} from "../../../services/storage.service";
import {ActivatedRoute, Router} from "@angular/router";
import {Message, TreeNode} from "primeng/primeng";
import {environment} from "../../../../environments/environment";
import {InventorymaintenanceService} from "../../inventorymaintenance.service";
import {PUblicMethod} from "../../public/PUblicMethod";

@Component({
  selector: 'app-malfunction-edit-inventory',
  templateUrl: './malfunction-edit-inventory.component.html',
  styleUrls: ['./malfunction-edit-inventory.component.scss']
})
export class MalfunctionEditInventoryComponent implements OnInit {

  initStatus = '';                       // 故障单状态
  malfNumber = '';                       // 服务单号

  malSourceOptins: any = [];             // 可选来源数据
  malSource: any;                        // 来源
  malImpactOptions: any = [];            // 影响度可选数据
  malImpact: any;                        // 影响度
  malUrgencyOptions: any = [];           // 紧急度可选数据
  malUrgency: any;                       // 紧急度
  malLevelOptions: any = [];             // 故障级别选项
  malLevel: any;                         // 故障级别
  malfPrority = '';                      // 优先级
  malDepPersonOptions: any = [];         // 分配个人可选数据
  malDepPerson: any;                     // 分配个人

  malStatus = '新建';                    // 状态
  reporter: TreeNode[] = [];             // 报告人
  zh: any;
  dealTime: Date;                        // 受理时间
  occurTime: Date;                       // 发生时间
  malDeadline = '';                      // 最终期限

  malTitle = '';                         // 故障单标题
  malDesc = '';                          // 故障单描述
  uploadedFiles = [];
  uploadRes = [];                        // 上传成功返回的文件路径对象
  ip: string;                            // 127.0.0.1:80
  message: Message[] = [];               // 交互提示弹出框
  msg: Message[] = [];                   // 验证弹出框

  belongSystem: TreeNode[] = [];         // 所属系统
  locationOccur: TreeNode[] = [];        // 发生地点
  relativeCategore: TreeNode[] = [];     // 关联目录
  relativeEquip: TreeNode[] = [];        // 关联设备编号
  selectedDepartment: TreeNode[] = [];   // 分配至部门
  departementDisplay: boolean;           // 树显示控制
  filesTree4: TreeNode[];                // 树的可选值
  selected: TreeNode[];                  // 树的选中值
  dialogHeader: string;                  // 组织树弹框标题
  currentTreeName: string;               // 当前要加载的树
  selectedMode: string;                  // 树的选择模式
  myForm: FormGroup;
  displayPersonel: boolean;              // 人员组织组件是否显示

  constructor(private maintenanceService: InventorymaintenanceService,
              private router: Router,
              private storageService: StorageService,
              private publicService: PublicService,
              private activatedRouter: ActivatedRoute,
              private fb: FormBuilder,
              private eventBusService: EventBusService) { }

  ngOnInit() {
    this.initForm();
    let initSid = this.activatedRouter.snapshot.paramMap.get('id');
    this.initStatus = this.activatedRouter.snapshot.paramMap.get('status');
    this.maintenanceService.getFlowChart( this.initStatus).subscribe(res => {
      this.eventBusService.maintenance.next(res);
    });
    this.zh = new PUblicMethod().initZh();
    this.dealTime = new Date();
    this.getOptions();
    this.getDepPerson();
    this.departementDisplay = false;
    this.ip = environment.url.management;
    this.initTrick(initSid);
  }
  initForm() {
    this.myForm = this.fb.group({
      'sid': '',
      'malfNumber': '',
      'malStatus': '',
      'reporterLabel': ['', Validators.required],
      'reporterFather': '',
      'reporterRemark': '',
      'dealTime': '',
      'occurTime': '',
      'malDeadline': '',
      'malImpact': '',
      'malUrgency': '',
      'malfPrority': '',
      'malLevel': '',
      'belongSystemLabel': '',
      'locationOccurLabel': '',
      'malTitle': ['', Validators.required],
      'malDesc': ['', Validators.required],
      'upload': '',
      'relativeCategoreLabel': '',
      'relativeEquipLabel': '',
      'selectedDepartmentLabel': '',
      'malDepPerson': ''
    });
  }
  initTrick(s) {
    this.maintenanceService.getTrick(s).subscribe(res => {
      console.log(res);
      let data = res['data'];
      if (res['errcode'] === '00000') {
        this.malfNumber = data['sid'];
        this.malSource = {name: data['fromx']};
        this.malStatus = data['status'];
        this.reporter['name'] = data['submitter'];
        this.reporter['organization'] = data['submitter_org'];
        this.reporter['mobile'] = data['submitter_phone'];
        this.reporter['pid'] = data['submitter_pid']
        this.reporter['oid'] = data['submitter_org_oid'];
        this.malDeadline = data['deadline'];
        this.malUrgency = { name: data['urgency'] };
        if (!data['influence']) {
          this.malImpact = { name: '请选择紧急度' };
        }else {
          this.malImpact = { name: data['influence'] };
        }
        if (!data['urgency']) {
          this.malUrgency = { name: '请选择紧急度' };
        }else {
          this.malUrgency = { name: data['urgency'] };
        }
        this.malfPrority = data['priority'];
        if (!data['level']) {
          this.malLevel = { name: '请选择故障级别'};
        }else {
          this.malLevel = { name: data['level'] };
        }
        if (!data['acceptor']) {
          this.malDepPerson = { name: '请选择人员'};
        }else {
          this.malDepPerson = {name: data['acceptor']};
        }
        this.belongSystem['label'] = data['bt_system'];
        this.locationOccur['label'] = data['addr'];
        this.malTitle = data['title'];
        this.malDesc = data['content'];
        this.relativeCategore['label'] = data['service'];
        this.relativeEquip['label'] = data['devices'];
        this.selectedDepartment['label'] = data['acceptor_org'];

        (data['accept_time']) && (this.dealTime = data['accept_time']);
        (data['occurrence_time']) && (this.occurTime = new Date(data['occurrence_time']));
      }else {
        this.message = [];
        this.message.push({severity: 'error', summary: '消息提示', detail: `获取故障单信息失败${res}`});
      }
    });
  }
  getOptions() {
    this.maintenanceService.getParamOptions().subscribe(res => {
      if (!res) {
        this.malSourceOptins = [];
        this.malImpactOptions = [];
        this.malUrgencyOptions = [];
        this.malLevelOptions = [];
      }else {
        this.malSourceOptins = res['来源'];
        this.malImpactOptions = res['影响度'];
        this.malUrgencyOptions = res['紧急度'];
        this.malLevelOptions = res['故障级别'];
      }
    });
  }
  onBeforeUpload(event) {
    let token = this.storageService.getToken('token');
    event.formData.append('access_token', token);
  }
  onUpload(event) {
    let xhrRespose = JSON.parse(event.xhr.response);
    if ( xhrRespose.errcode && xhrRespose.errcode === '00000' ) {
      this.uploadRes = xhrRespose['datas'];
      this.message = [];
      this.message.push({severity: 'success', summary: '消息提示', detail: '上传成功'});
    }else {
      this.message = [];
      this.message.push({severity: 'error', summary: '消息提示', detail: `上传失败${xhrRespose.errmsg}`});
    }
  }
  // 部门组织树模态框
  showTreeDialog(which: string) {
    this.currentTreeName = which;
    this.selected = [];
    this.filesTree4 = [];
    this.departementDisplay = true;
    switch (which) {
      case 'reporter':
        this.departementDisplay = false;
        this.displayPersonel = true;
        break;
      case 'belongSystem':
        this.dialogHeader = '请选择所属系统';
        this.selectedMode = 'single';
        this.publicService.getMalfunctionBasalDatas('1.006', '1').subscribe(res => {
          this.filesTree4 = res;
        });
        break;
      case 'locationOccur':
        this.dialogHeader = '请选择发生地点';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
      case 'relativeCategore':
        this.dialogHeader = '请选择关联服务目录';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
      case 'relativeEquip':
        this.dialogHeader = '请选择关联设备编号';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
      case 'selectedDepartment':
        this.dialogHeader = '请选择部门';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
    }
  }
  // 组织树懒加载
  nodeExpand(event) {
    switch ( this.currentTreeName ) {
      case 'belongSystem':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
      case 'locationOccur':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
      case 'relativeCategore':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
      case 'relativeEquip':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
      case 'selectedDepartment':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
    }
  }
  nodeSelect(event) {
    console.log(event);
  }
  // 清空组织树选中内容
  clearTreeDialog (which) {
    switch ( which ) {
      case 'reporter':
        this.reporter = [];
        break;
      case 'belongSystem':
        this.belongSystem = [];
        break;
      case 'locationOccur':
        this.locationOccur = [];
        break;
      case 'relativeCategore':
        this.relativeCategore = [];
        break;
      case 'relativeEquip':
        this.relativeEquip = [];
        break;
      case 'selectedDepartment':
        this.selectedDepartment = [];
        this.getDepPerson();
        break;
    }
  }
  // 组织树最后选择
  closeTreeDialog() {
    switch ( this.currentTreeName ) {
      case 'belongSystem':
        this.belongSystem = this.selected;
        break;
      case 'locationOccur':
        this.locationOccur = this.selected;
        break;
      case 'relativeCategore':
        this.relativeCategore = this.selected;
        break;
      case 'relativeEquip':
        this.relativeEquip = this.selected;
        break;
      case 'selectedDepartment':
        this.selectedDepartment = this.selected;
        this.getDepPerson(this.selected['oid']);
        break;
    }
    this.departementDisplay = false;
  }
  getDepPerson(oid?) {
    this.publicService.getApprovers(oid).subscribe(res => {
      if (!res) {
        this.malDepPersonOptions = [];
      }else {
        this.malDepPersonOptions = res;
      }
    });
  }
  onFocus() {
    this.getPrority();
  }
  // 计算优先级
  getPrority() {
    if ( this.malImpact && this.malUrgency ) {
      this.maintenanceService.getPrority( this.malImpact['name'], this.malUrgency['name'] ).subscribe(res => {
        if (res) {
          this.malfPrority = res['priority'];
          this.getDeadline();
        }
      });

    }
  }
  // 计算最终期限
  getDeadline() {
    if ( this.malImpact && this.malUrgency && this.malfPrority ) {
      this.maintenanceService.getDeadline( this.malImpact['name'], this.malUrgency['name'], this.malfPrority ).subscribe(res => {
        if (res) {
          this.malDeadline = res['deadline'];
        }
      });
    }
  }
  // 日期格式化
  static formatDate(date) {
    if ( date ) {
      return date.getFullYear() +
        '-' + pad( date.getMonth() + 1 ) +
        '-' + pad( date.getDate() ) +
        ' ' + pad( date.getHours() ) +
        ':' + pad( date.getMinutes() ) +
        ':' + pad( (date.getSeconds() / 1000).toFixed() );
    }else {
      return date;
    }
    function pad (num) {
      if ( num < 10 ) {
        return '0' + num;
      }
      return num;
    }

  }
  //  保存故障单
  save() {
    let pathArray = [];
    if ( this.uploadRes.length > 0 ) {
      for ( let val of this.uploadRes ) {
        pathArray.push( val['path'] );
      }
    }
    console.log(this.malLevel);
    let paper = {
      'sid': this.malfNumber,
      'name': '',
      'fromx': this.malSource['name'],
      'status': this.malStatus,
      'submitter': this.reporter['name'],
      'submitter_pid': this.reporter['pid'],
      'submitter_org': this.reporter['organization'],
      'submitter_org_oid': this.reporter['oid'],
      'submitter_phone': this.reporter['mobile'],
      // 'occurrence_time': MalfunctionAddComponent.formatDate( this.occurTime ),
      'deadline': this.malDeadline,
      'influence': this.malImpact['name'],
      'urgency': this.malUrgency['name'],
      'priority': this.malfPrority,
      'level': this.malLevel['name'],
      'bt_system': '',
      'addr': this.locationOccur['label'],
      'service': this.relativeCategore['label'],
      'devices': this.relativeEquip['label'],
      'title': this.malTitle,
      'content': this.malDesc,
      'attachment': pathArray,
      'acceptor': this.malDepPerson,
    };
    this.maintenanceService.saveTicket( paper ).subscribe(res => {
      if ( res === '00000' ) {
        this.message = [];
        this.message.push({severity: 'success', summary: '消息提示', detail: '保存成功'});
        window.setTimeout(() => {
          this.router.navigateByUrl('/index/maintenance/malfunctionBase');
        }, 1500);
      }else {
        this.message = [];
        this.message.push({severity: 'error', summary: '消息提示', detail: `保存失败${res}`});
      }
    });
  }
  //  提交故障单
  submitTrick() {
    let pathArray = [];
    if ( this.uploadRes.length > 0 ) {
      for ( let val of this.uploadRes ) {
        pathArray.push( val['path'] );
      }
    }
    console.log(this.reporter);
    let paper = {
      'sid': this.malfNumber,
      'name': '',
      'fromx': this.malSource['name'],
      'status': '待分配',
      'submitter': this.reporter['name'],
      'submitter_pid': this.reporter['pid'],
      'submitter_org': this.reporter['organization'],
      'submitter_org_oid': this.reporter['oid'],
      'submitter_phone': this.reporter['mobile'],
      'occurrence_time': PUblicMethod.formateEnrtyTime( this.occurTime ),
      'deadline': this.malDeadline,
      'influence': this.malImpact['name'],
      'urgency': this.malUrgency['name'],
      'priority': this.malfPrority,
      'level': this.malLevel['name'],
      'bt_system': this.belongSystem['label'],
      'addr': this.locationOccur['label'],
      'service': this.relativeCategore['label'],
      'devices': this.relativeCategore['label'],
      'title': this.malTitle,
      'content': this.malDesc,
      'attachment': pathArray,
      'acceptor': this.malDepPerson['name'],
      'acceptor_pid': this.malDepPerson['pid'],
      'acceptor_org': this.malDepPerson['label'],
      'acceptor_org_oid': this.malDepPerson['oid']
    };
    if (  !this.reporter['name']
      || !this.occurTime
      || !this.malDeadline
      || !this.malImpact
      || !this.malUrgency
      || !this.belongSystem['label']
      || !this.malTitle
      || !this.malDesc
    ) {
      this.showError();
    }else {
      this.submitPost(paper);
    }
  }
  showError() {
    this.msg = [];
    this.msg.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
  }
  submitPost(paper) {
    this.maintenanceService.submitTicket( paper ).subscribe(res => {
      if ( res === '00000' ) {
        this.message = [];
        this.msg = [];
        this.message.push({severity: 'success', summary: '消息提示', detail: '操作成功'});
        window.setTimeout(() => {
          this.router.navigateByUrl('/index/maintenance/malfunctionBase');
        }, 1100);

      }else {
        this.message = [];
        this.message.push({severity: 'error', summary: '消息提示', detail: `操作失败${res}`});
      }
    });
  }
  //  提交并分配故障单
  submitAndDistribute() {
    let pathArray = [];
    if ( this.uploadRes.length > 0 ) {
      for ( let val of this.uploadRes ) {
        pathArray.push( val['path'] );
      }
    }
    let paper = {
      'sid': this.malfNumber,
      'name': '',
      'fromx': this.malSource['name'],
      'status': '待接受',
      'submitter': this.reporter['name'],
      'submitter_pid': this.reporter['pid'],
      'submitter_org': this.reporter['organization'],
      'submitter_org_oid': this.reporter['oid'],
      'submitter_phone': this.reporter['mobile'],
      'occurrence_time': PUblicMethod.formateEnrtyTime( this.occurTime ),
      'deadline': this.malDeadline,
      'influence': this.malImpact['name'],
      'urgency': this.malUrgency['name'],
      'priority': this.malfPrority,
      'level': this.malLevel['name'],
      'bt_system': this.belongSystem['label'],
      'addr': this.locationOccur['label'],
      'service': this.relativeCategore['label'],
      'devices': this.relativeCategore['label'],
      'title': this.malTitle,
      'content': this.malDesc,
      'attachment': pathArray,
      'acceptor': this.malDepPerson['name'],
      'acceptor_pid': this.malDepPerson['pid'],
      'acceptor_org': this.malDepPerson[''],
      'acceptor_org_oid': this.malDepPerson['oid']
    };
    console.log(paper);

    if (  !this.reporter['name']
      || !this.occurTime
      || !this.malDeadline
      || !this.malImpact
      || !this.malUrgency
      || !this.belongSystem['label']
      || !this.malTitle
      || !this.malDesc
      || !String(this.selectedDepartment)
    ) {
      this.showError();
      console.log(!this.reporter['name']);
      console.log(!this.occurTime);
      console.log(!this.malDeadline);
      console.log(this.malImpact);
      console.log(!this.malUrgency);
      console.log(!this.belongSystem['label']);
      console.log(!this.malTitle);
      console.log(!this.malDesc);
      console.log(!String(this.selectedDepartment));
    }else {
      this.submitPost(paper);
    }
  }

  dataEmitter(event) {
    console.log(event);
    this.reporter = event;

  }
  displayEmitter(event) {
    this.displayPersonel = event;
  }


}
